<template>
  <div>
    <el-upload
      action="#"
      list-type="picture"
      :multiple="false"
      :show-file-list="showFileList"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      :http-request="uploadActionRequest"
    >
      <i class="el-icon-plus el-upload-btn"></i>
      <div slot="tip" class="el-upload__tip icon-list__tips">
        只能上传jpg/png文件，且不超过10MB
      </div>
    </el-upload>
    <el-dialog
      title="图片预览"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      append-to-body
    >
      <img width="100%" :src="fileList[0].url" :alt="fileList[0].name" />

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { fileUpload } from "@/api/fileupload";
import { mapState } from "vuex";
export default {
  name: "singleUpload",
  props: {
    value: String,
  },

  //计算属性
  computed: {
    //state:他是咱们大仓库中的state
    ...mapState({
      fileDomain: (state) => state.fileupload.fileDomain,
    }),
    imageUrl() {
      return this.value;
    },
    imageName() {
      if (this.value != null && this.value !== "") {
        return this.value.substr(this.value.lastIndexOf("/") + 1);
      } else {
        return null;
      }
    },
    fileList() {
      return [
        {
          name: this.imageName,
          url: this.fileDomain + "/" + this.imageUrl,
        },
      ];
    },
    showFileList: {
      get: function () {
        return (
          this.value !== null && this.value !== "" && this.value !== undefined
        );
      },
      set: function (newValue) {},
    },
  },
  data() {
    return {
      dialogVisible: false,
    };
  },
  methods: {
    async uploadActionRequest(fileData) {
      let fd = new FormData();
      fd.append("file", fileData.file);
      const resp = await fileUpload(fd);
      return resp;
    },
    emitInput(val) {
      this.$emit("input", val);
    },
    handleRemove(file, fileList) {
      this.emitInput("");
    },
    handlePreview(file) {
      this.dialogVisible = true;
    },
    beforeUpload(file) {
      let _self = this;
      // 验证文件格式和大小
    },
    handleUploadSuccess(res, file, fileList) {
      console.log("上传成功...", res);
      const resData = res.data;
      this.fileList.pop();
      this.fileList.push({
        name: file.name,
        url: resData.fileUrl,
        shortUrl: resData.fileKey,
      });
      this.showFileList = true;
      this.value = resData.shortUrl;
      this.emitInput(resData.shortUrl);
    },
  },
};
</script>
<style>
.el-upload {
  width: 60px;
  height: 60px;
  border: 1px dashed #e2e2e2;
  text-align: center;
  line-height: 60px;
}
.el-upload:hover {
  border: 1px dashed #1890ff;
}

.el-upload:hover .el-upload-btn {
  color: #1890ff;
}
</style>


